package com.learn.concurrent.lock;

public class Synchronized_01 {

    public static void main(String[] args) {
        System.out.println("使用关键字synchronized");

        SyncThread syncThread = new SyncThread();
        Thread thread1 = new Thread(syncThread, "syncThread1");
        thread1.start();

        Thread thread2 = new Thread(syncThread, "syncThread2");
        //Thread thread2 = new Thread(new SyncThread(), "syncThread2");
        thread2.start();

    }
}

/**
 * 1. 修饰一个代码块，被修饰的代码块称为同步语句块，其作用的范围是大括号{}括起来的代码，
 * 作用的对象是调用这个代码块的对象；
 * Synchronized作用于整个方法的写法。
 * 方法一：
 * public synchronized void method()
 * {
 *    // todo
 * }
 * 方法二：
 * public void method()
 * {
 *    synchronized(this) {
 *
 *    }
 * }
 */
class SyncThread implements Runnable {

    private static int count;

    /*@Override
    public void run() {
        synchronized (this) {
            for(int i=0;i<5;i++){
                try {
                    System.out.println("线程名:"+Thread.currentThread().getName() + ":" + (count++));
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }*/

    @Override
    public synchronized void run() {
        for (int i = 0; i < 5; i++) {
            try {
                System.out.println("线程名:" + Thread.currentThread().getName() + ":" + (count++));
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    public int getCount() {
        return count;
    }
}

